﻿using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace MiP.XmlCmd.Shell.Variables
{
    public class XmlVariableParser : IXmlVariableParser
    {
        public ICollection<KeyValuePair<string, string>> ParseVariables(XElement xml)
        {
            if (xml.Name != "variables")
                throw new XmlException("Expected element with name 'variables' but found: " + xml.Name);

            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();

            foreach (XElement element in xml.Elements())
            {
                if (element.Name != "set")
                    throw new XmlException("All elements must be named 'set'.");

                IEnumerable<KeyValuePair<string, string>> variables = element.Attributes()
                    .Select(xAttribute => new KeyValuePair<string, string>(xAttribute.Name.LocalName, xAttribute.Value));
                result.AddRange(variables);
            }

            return result;
        }
    }
}